<?php

namespace app\api\controller;

use app\api\model\Group;
use app\api\model\GroupUser;
use app\common\controller\Api;
use RongCloud\Lib\Request;
use RongCloud\Lib\Utils;

/**
 * 融云
 */
class RongYun extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 创建群组
     *
     * @param $Group array 创建群组 参数
     */
    public function createGroup()
    {
        $Group['name'] = input('group_name');//群组名称
        $user_ids = input('user_ids');//群成员id(1,2,3,4)
        if (empty($user_ids)) $this->error('参数错误');
        $user = explode(',', $user_ids);
        $Group['id'] = rand() . '_' . $user[0];//群主id
        foreach ($user as $k => $v) {
            $Group['members'][$k] = $v;
        }
        $Group = (new Utils())->rename($Group, [
            'id' => 'groupId',
            'name' => 'groupName',
            'members' => 'userId',
        ]);
        $result = (new Request())->Request('group/create', $Group);
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            $groupCreate = Group::create(['group_id' => $Group['groupId'], 'group_name' => $Group['groupName']]);
            $groupCreate['introduction'] = null;
            $groupCreate['avatar'] = null;
            foreach ($Group['userId'] as $k => $v) {
                $data['auth'] = 0;
                if ($k == 0) {
                    $data['auth'] = 1;
                }
                $data['user_id'] = $v;
                $data['group_id'] = $Group['groupId'];
                GroupUser::create($data);
            }
            $this->success('创建成功', $groupCreate);
        }
        $this->error('创建失败');
    }

    /**
     * 加入群组
     *
     * @param $Group array 加入群组 参数
     * @param
     * $Group = [
     * 'id'=> 'watergroup',//群组 id
     * 'name'=>"watergroup",//群组名称
     * 'member'=>['id'=> 'group999'],//群成员信息
     * ];
     * @throws \think\exception\DbException
     */
    public function groupJoins(array $Group = [])
    {
        $Group['id'] = input('id');//群主id
        $Group['name'] = input('group_name');//群组名称
        $user_ids = input('user_ids');//群成员id(1,2,3,4)
        $user = explode(',', $user_ids);
        foreach ($user as $k => $v) {
            $Group['member'][$k] = $v;
        }
        $Group = (new Utils())->rename($Group, [
            'id' => 'groupId',
            'name' => 'groupName',
            'member' => 'userId',
        ]);
        $result = (new Request())->Request('group/join', $Group);
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            foreach ($Group['userId'] as $v) {
                $data['user_id'] = $v;
                $data['group_id'] = $Group['groupId'];
                if (GroupUser::get($data)) continue;
                GroupUser::create($data);
            }
            $this->success('加入成功');
        }
        $this->error('加入失败');
    }

    /**
     * 退出群组
     *
     * @param $Group array 退出群组 参数
     * @param
     * $Group = [
     * 'id'=> 'watergroup',//群组 id
     * 'member'=>['id'=> 'group999'],//群成员信息
     * ];
     */
    public function groupQuit(array $Group = [])
    {
        $Group['id'] = input('id');//群主id
        $user_ids = input('user_id');
        $Group['member'][] = $user_ids;
        $Group = (new Utils())->rename($Group, [
            'id' => 'groupId',
            'member' => 'userId',
        ]);
        $result = (new Request())->Request('group/quit', $Group);
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            $arr = explode(',', $Group['userId'][0]);
            foreach ($arr as $v) {
                $data['user_id'] = $v;
                $data['group_id'] = $Group['groupId'];
                GroupUser::destroy($data);
            }
            $this->success('退出成功');
        }
        $this->error('退出失败');
    }

    /**
     * 修改群信息
     *
     * @param $Group array 修改群信息 参数
     * @param
     * $Group = [
     * 'id'=> 'watergroup',//群组 id
     * 'name'=>"watergroup"//群名称
     * ];
     */
    public function update(array $Group = [])
    {
        $Group['id'] = input('id');//群组id
        $Group['name'] = input('group_name');//群组名称
        $Group = (new Utils())->rename($Group, [
            'id' => 'groupId',
            'name' => 'groupName',
        ]);
        $result = (new Request())->Request('group/refresh', $Group);
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            Group::update(['group_name' => $Group['groupName']], ['group_id' => $Group['groupId']]);
            $this->success('修改成功');
        }
        $this->error('修改失败');
    }

    /**
     * 获取群信息
     *
     * @param $Group array 获取群信息 参数
     * @param
     * $Group = [
     * 'id'=> 'watergroup',//群组 id
     * ];
     */
    public function groupGet(array $Group = [])
    {
        $Group['id'] = input('id');//群组id
        $Group = (new Utils())->rename($Group, [
            'id' => 'groupId',
        ]);
        $result = (new Request())->Request('group/user/query', $Group);
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            $user = [];
            foreach ($result['users'] as $k => $v) {
                $user[$k]['user_id'] = $v['id'];
                $userInfo = model('user_info')->where('user_id', $v['id'])
                    ->field('avatar,username,status as auth_status,birthday,gender,signature')->find();
                $user[$k]['avatar'] = $userInfo['avatar'];
                $user[$k]['username'] = $userInfo['username'];
                $user[$k]['auth_status'] = $userInfo['auth_status'];
                $user[$k]['gender'] = $userInfo['gender'];
                $user[$k]['signature'] = $userInfo['signature'];
                $user[$k]['age'] = user_age($userInfo['birthday']);
                $user[$k]['members'] = model('members')->where('user_id', $v['id'])->value('status') ?? 0;
                $user[$k]['auth'] = model('group_user')->where(['group_id'=>$Group['groupId'],'user_id'=>$v['id']])->value('auth');
            }
            $this->success('成功', $user);
        }
        $this->error('失败');
    }

    /**
     * 添加群组禁言
     *
     * @param $Group array 添加群组禁言 参数
     * @param
     * $Group = [
     * 'id'=> 'ujadk90ha',//群组 id
     * 'members'=>[ //禁言人员列表
     * ['id'=> 'ujadk90ha']
     * ]
     * ,
     * 'minute'=>50  //    禁言时长
     * ];
     */
    public function groupGagAdd(array $Group = [])
    {
        $Group['id'] = input('id');//群组id
        $Group['minute'] = '50';//群组名称
        $user_ids = input('user_ids');//群成员id(1,2,3,4)
        $user = explode(',', $user_ids);
        foreach ($user as $k => $v) {
            $Group['members'][$k] = $v;
        }
        $Group = (new Utils())->rename($Group, [
            'id' => 'groupId',
            'members' => 'userId'
        ]);
        $result = (new Request())->Request('group/user/gag/add', $Group);
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            $this->success('禁言成功');
        }
        $this->error('禁言失败');
    }

    /**
     * 解除禁言
     *
     * @param $Group array 解除禁言 参数
     * @param
     * $Group = [
     * 'id'=> 'ujadk90ha',//群组 id
     * 'members'=>[ //解除禁言人员列表
     * ['id'=> 'ujadk90ha']
     * ]
     * ];
     */
    public function groupGagRemove(array $Group = [])
    {
        $Group['id'] = input('id');//群组id
        $user_ids = input('user_ids');//群成员id(1,2,3,4)
        $user = explode(',', $user_ids);
        foreach ($user as $k => $v) {
            $Group['members'][$k] = $v;
        }
        $Group = (new Utils())->rename($Group, [
            'id' => 'groupId',
            'members' => 'userId'
        ]);
        $result = (new Request())->Request('group/user/gag/rollback', $Group);
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            $this->success('解除禁言成功');
        }
        $this->error('解除禁言失败');
    }

    /**
     * 查询禁言成员列表
     *
     * @param $Group array 解除禁言 参数
     * @param
     * $Group = [
     * 'id'=> 'ujadk90ha',//群组 id
     * ];
     * @return array
     */
    public function getList(array $Group = [])
    {
        $conf = $this->conf['getList'];
        $verify = $this->verify['group'];
        $verify = ['id' => $verify['id']];
        $error = (new Utils())->check([
            'api' => $conf,
            'model' => 'group',
            'data' => $Group,
            'verify' => $verify
        ]);
        if ($error) return $error;
        $Group = (new Utils())->rename($Group, [
            'id' => 'groupId',
        ]);
        $result = (new Request())->Request($conf['url'], $Group);
        $result = (new Utils())->responseError($result, $conf['response']['fail']);
        if ($result['code'] == 200) {
            $result = (new Utils())->rename($result, ['users' => 'members']);
            foreach ($result['members'] ?: [] as $k => &$v) {
                $v = (new Utils())->rename($v, ['userId' => 'id']);
            }
        }
        return $result;
    }

    /**
     * @param $User array 用户注册
     * @param
     * $User = [
     * 'id'=> 'ujadk90ha',//用户id
     * 'name'=> 'Maritn',//用户名称
     * 'portrait'=> 'http://7xogjk.com1.z0.glb.clouddn.com/IuDkFprSQ1493563384017406982' //用户头像
     * ];
     * @return array
     */
    public function register(array $User = [])
    {
        $User = (new Utils())->rename($User, [
            'id' => 'userId',
            'portrait' => 'portraitUri'
        ]);
        $result = (new Request())->Request('user/getToken', $User);
        $result = json_decode($result, true);
        return $result;
    }

    /**
     * @param $User array 用户信息更新
     * @param
     * $User = [
     * 'id'=> 'ujadk90ha',//用户id
     * 'name'=> 'Maritn',//用户名称
     * 'portrait'=> 'http://7xogjk.com1.z0.glb.clouddn.com/IuDkFprSQ1493563384017406982' //用户头像
     * ];
     * @return array
     */
    public function updateRefresh(array $User = [])
    {
        $User = (new Utils())->rename($User, [
            'id' => 'userId',
            'portrait' => 'portraitUri'
        ]);
        $result = (new Request())->Request('user/refresh', $User);
        $result = json_decode($result, true);
        return $result;
    }

    /**
     * @param $Message array 系统广播消息
     * @param
     * $Message = [
     * 'senderId'=> '__system__',//发送人 id
     * 'targetId'=> 'markoiwm',//接收放 id
     * "objectName"=>'RC:TxtMsg',//消息类型
     * 'content'=>['content'=>'你好，小明']//消息内容
     * ];
     * @return array
     */
    public function broadcast($Message)
    {
        $Message = (new Utils())->rename($Message, [
            'senderId' => 'fromUserId',
            'targetId' => 'toUserId'
        ]);
        $result = (new Request())->Request('message/system/publish', $Message);
        $result = json_decode($result, true);
        return $result;
    }

    /**
     * @param $User array 添加黑名单
     * @param
     * $user = [
     * 'user_id'=> 'ujadk90ha',//用户 id
     * 'black_id'=> ['kkj9o01'] //需要添加黑名单的人员列表
     * ];
     * @return array
     */
    public function blackAdd(array $User = [])
    {
        $User = (new Utils())->rename($User, [
            'user_id' => 'userId',
            'black_id' => 'blackUserId'
        ]);
        $result = (new Request())->Request('user/blacklist/add', $User);
        $result = json_decode($result, true);
        return $result;
    }

    /**
     * @param $User array 移除黑名单
     * @param
     * $user = [
     * 'user_id'=> 'ujadk90ha',//用户 id
     * 'black_id'=> ['kkj9o01'] //需要移除黑名单的人员列表
     * ];
     * @return array
     */
    public function blackRemove(array $User = [])
    {
        $User = (new Utils())->rename($User, [
            'user_id' => 'userId',
            'black_id' => 'blackUserId'
        ]);
        $result = (new Request())->Request('user/blacklist/remove', $User);
        $result = json_decode($result, true);
        return $result;
    }
}